package top.jybill.service.Impl;

import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import top.jybill.dao.IOrderDao;
import top.jybill.dao.IOrderTravellerDao;
import top.jybill.dao.IProductDao;
import top.jybill.domain.MyPageInfo;
import top.jybill.domain.Order;
import top.jybill.domain.Product;
import top.jybill.domain.Traveller;
import top.jybill.exception.MyException;
import top.jybill.service.IProductService;
import top.jybill.utils.BeanUtil;

import java.util.List;

@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class ProductServiceImpl implements IProductService {

  @Autowired
  private IProductDao productDao;
  @Autowired
  private IOrderTravellerDao orderTravellerDao;
  @Autowired
  private IOrderDao orderDao;

  public List<Product> findAll() {
    return productDao.findAll();
  }

  @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
  public void saveProduct(Product product) throws Exception {
    System.out.println(product);
    if (!BeanUtil.exComplete(product, "id")) {
      throw new MyException("bean不完整");
    }
    productDao.saveProduct(product);
  }

  public MyPageInfo findProductByPage(MyPageInfo page) {
    if (page.getQuery().length() < 1 || "null".equalsIgnoreCase(page.getQuery())) {
      page.setQuery(null);
    } else {
      page.setQuery("%" + page.getQuery() + "%");
    }

    PageHelper.startPage(page.getPageNum(), page.getPageSize());
    List<Product> products = productDao.findProductsByPage(page);
    return new MyPageInfo(products);
  }

  @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
  public void delProduct(String pid) {
    // 是否有订单外键关联商品
    List<Order> orders = orderDao.findOrderByPid(pid);
    if (orders != null) {
      // 存在外键关联
      for (Order order : orders) {
        List<Traveller> traveller = orderTravellerDao.findTravellerByOid(order.getId());
        // 是否有订单关联旅客
        if (traveller != null) {
          orderTravellerDao.delOrderTraveller(order.getId());// 存在关联旅客}
        }

        orderDao.delOrderByPid(pid);// 删除所有订单
      }
      productDao.delProduct(pid); // 删除所有产品
    }
  }

  /**
   * 更新产品
   * @param product
   */
  @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
  public void updateProduct(Product product) {
    productDao.updateProduct(product);
  }

  /**
   * 根据商品id查商品
   * @param pid
   * @return
   */
  public Product findProductByPid(String pid) {
    return productDao.findProductByPid(pid);
  }
}
